<?php

error_reporting(E_STRICT | E_ALL);

// Provide AdWords login information.
$email = 'info@ua-solutions.com';
$password = 'uasolutions';

$params = array(
    'Email' => $email,
    'Passwd' => $password,
    'accountType' => 'GOOGLE',
    'service' => 'adwords',
    'source' => 'AdWords API PHP Code Example');

$url = 'https://www.google.com/accounts/ClientLogin';

// Make request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);

// Parse response.
$lines = explode("\n", $response);
foreach ($lines as $line) {
  $parts = explode('=', $line, 2);
  if ($parts[0] == 'Auth') {
    $authToken = $parts[1];
  }
  if ($parts[0] == 'Error') {
    $error = $parts[1];
  }
}

// Display results.
if (isset($authToken)) {
  //print 'Auth token: ' . $authToken . "\n";
} else if (isset($error)) {
  print 'Error: ' . $error . "\n";
}

// Provide header information.
//$authToken = 'INSERT_AUTH_TOKEN_HERE';
$clientCustomerId = '432-845-3367';
$userAgent = 'uasolutions: AdWords API PHP Code Example';
$developerToken = 'pEGGOZ84xYlJktXyXJnSKg';
// Provide header information.
$apiVersion = 'v201302';
// Create report definition XML.
$reportDefinition = <<<EOT
<reportDefinition xmlns="https://adwords.google.com/api/adwords/cm/v201302">
  <selector>
    <fields>CampaignId</fields>
		<fields>AdGroupName</fields>
		<fields>CampaignName</fields>
    <fields>Id</fields>
    <fields>Impressions</fields>
    <fields>Clicks</fields>
    <fields>Cost</fields>
    <predicates>
      <field>Status</field>
      <operator>IN</operator>
      <values>ENABLED</values>
      <values>PAUSED</values>
    </predicates>	
  </selector>
  <reportName>Custom Adgroup Performance Report</reportName>
  <reportType>ADGROUP_PERFORMANCE_REPORT</reportType>
  <dateRangeType>LAST_7_DAYS</dateRangeType>
  <downloadFormat>CSV</downloadFormat>
</reportDefinition>
EOT;

// Create parameters.
$params = array('__rdxml' => $reportDefinition);

// Create headers.
$headers = array();
$headers[]= 'Authorization: GoogleLogin auth=' . $authToken;
$headers[]= 'clientCustomerId: ' . $clientCustomerId;
$headers[]= 'developerToken: ' . $developerToken;

$downloadPath = 'report.csv';
$url = 'https://adwords.google.com/api/adwords/reportdownload/v201302';

$file = fopen($downloadPath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($file);

if ($code == 200) {
  //printf("Report downloaded to: %s\n", $downloadPath);
	$line = readfile_chunked(__DIR__."/report.csv");
	
	$arrTitle = str_getcsv($line[1]);
	$id = $_GET['id'];
	for($k=2;$k < count($line);$k++) 
	{
		$arrData = str_getcsv($line[$k]);
		if($arrData[0] == $id) break;
	}
	
} else {
  $file = fopen($downloadPath, 'r');
  $error = fread($file, 1024);
  fclose($file);
  printf("Error: %s\n", $error);
}

function readfile_chunked ($filename,$type='array') {
	if(!is_file($filename)) {
		return 404;
	}
	if(!is_readable($filename)) {
		return 403;
	}

	$chunk_array=array();
	$chunksize = 1*(1024*1024); // how many bytes per chunk
	$buffer = '';
	$handle = fopen($filename, 'rb');
	if ($handle === false) {
	 return false;
	}
	while (!feof($handle)) {
			switch($type)
			{
					case'array':
					// Returns Lines Array like file()
					$st = fgets($handle, $chunksize);
					if(trim($st)) {
						$lines[] = $st;
					}
					break;
					case'string':
					// Returns Lines String like file_get_contents()
					$lines = fread($handle, $chunksize);
					break;
			}
	}
	 fclose($handle);
	 //print_r($lines);
	 return $lines;
} 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html slick-uniqueid="3" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" dir="ltr" lang="en-gb"><!-- Footer --><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="generator" content="Humming! - Shopping cart">
  <title>Hummings - Administration</title>
  <script src="index_files/global.js" type="text/javascript"></script>
  <script src="index_files/jquery.js" type="text/javascript"></script>
  <script src="index_files/mootools-core.js" type="text/javascript"></script>
  <script src="index_files/core.js" type="text/javascript"></script>
  <script src="index_files/mootools-more.js" type="text/javascript"></script>
<!-- Load system style CSS -->
<link rel="stylesheet" href="index_files/system.css" type="text/css">

<!-- Load Template CSS -->
<link href="index_files/template.css" rel="stylesheet" type="text/css">

<!-- Load additional CSS styles for colors -->
<link href="index_files/colour_standard.css" rel="stylesheet" type="text/css">

<!-- Load additional CSS styles for rtl sites -->

<!-- Load specific language related css -->

<!-- Load additional CSS styles for bold Text -->

<!-- Load additional CSS styles for Internet Explorer -->
<!--[if IE 8]>
	<link href="insite/templates/hathor/css/ie8.css" rel="stylesheet" type="text/css" />
<![endif]-->
<!--[if IE 7]>
	<link href="insite/templates/hathor/css/ie7.css" rel="stylesheet" type="text/css" />
<![endif]-->
<!--[if lte IE 6]>
	<link href="insite/templates/hathor/css/ie6.css" rel="stylesheet" type="text/css" />
<![endif]-->

<!-- Load Template JavaScript -->
<script type="text/javascript" src="index_files/template.js"></script>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['barchart', 'table']});
    </script>
    <script type="text/javascript">
    var visualization;

    var sortData = new google.visualization.DataTable();
    sortData.addColumn('string', 'name');
    sortData.addColumn('number', 'Clicks');
		<?
		echo "sortData.addRows(5);\n";
		for($i=4;$i<count($arrTitle);$i++) {
			echo "sortData.setCell(".($i-4).", 0, '".$arrTitle[$i]."');\n";
		}
		
		for($j=4;$j<count($arrData);$j++) {
			echo "sortData.setCell(".($j-4).", 1, ".$arrData[$j].");\n";
		}		
		?>
			
    function drawVisualization() {
      var visualization = new google.visualization.LineChart(document.getElementById('visualization'));
      visualization.draw(sortData, {legend: 'bottom'});
						
      var table = new google.visualization.Table(document.getElementById('table'));
      table.draw(sortData, null);
    
      var chart = new google.visualization.BarChart(document.getElementById('chart'));
      chart.draw(sortData, null);
    
      google.visualization.events.addListener(table, 'sort',
          function(event) {
            sortData.sort([{column: event.column, desc: !event.ascending}]);
            chart.draw(sortData, null);
          });
    }
    

    google.setOnLoadCallback(drawVisualization);
    </script>
<link href="index_files/style.css" rel="stylesheet" type="text/css">
<link href="index_files/forms.css" rel="stylesheet" type="text/css">
<link href="index_files/tooltip.htm" rel="stylesheet" type="text/css">


</head>
<body id="minwidth-body">
<div id="containerwrap"> 
  <!-- Header Logo -->
  <div role="banner" id="header"> 
    
    <!-- Site Title and Skip to Content -->
    <div class="title-ua">
      <h1 class="title">Administration</h1>
      <div id="skiplinkholder">
        <p><a id="skiplink" href="#skiptarget">Skip to Main Content</a></p>
      </div>
    </div>
  </div>
  <!-- end header --> 
  
  <!-- Main Menu Navigation -->
  <div role="navigation" id="nav">
    <div id="module-menu">
		<h2 class="element-invisible">Main Menu</h2>
<ul id="menu">
  <li class="node"> <a href="#">Site</a>
    <ul>
      <li class="separator"><span></span></li>
      <li><a class="icon-16-config" href="#">Global Configuration</a></li>
      <li class="separator"><span></span></li>
      <li><a class="icon-16-logout" href="#">Logout</a></li>
    </ul>
  </li>
</ul>
</div>
    <div class="clr"></div>
  </div>
  <!-- end nav --> 
  
  <!-- Status Module -->
  <div id="module-status"> <span class="loggedin-users">0 Visitors</span><span class="backloggedin-users">1 Admin</span><span class="no-unread-messages"><a href="#">0</a></span> <span class="viewsite"><a href="#" target="_blank">View Site</a></span><span class="logout"><a href="#">Log out</a></span> </div>
  <!-- main --> 
  <div id="content">

		<!-- Component Title -->
			<div class="pagetitle icon-48-cpanel"><h2>Control Panel</h2></div>

		<!-- System Messages -->
		
<div id="system-message-container">
</div>
		<!-- Sub Menu Navigation -->
		<div id="no-submenu"></div>
   		<div class="clr"></div>

		<!-- Beginning of Actual Content -->
		<div role="main" id="element-box">
			<p id="skiptargetholder"><a id="skiptarget" class="skip" tabindex="-1"></a></p>

				<div class="adminform">

					<!-- Display the Quick Icon Shortcuts -->
					<div class="cpanel-icons">
						<div class="cpanel"><div class="icon-wrapper">
            <div>
              <h3>Campaign: <?=$arrData[2]?></h3>
            </div>
            <br />
            <div id="table"></div>
            <div id="chart" style="height: 300px; width: 300px;"></div>
            <div id="visualization" style="height: 400px; width: 400px;"></div>                       
            </div></div>

					</div>

					<!-- Display Admin Information Panels -->

				</div>
				<div class="clr"></div>

		</div><!-- end element-box -->

		<noscript>
			Warning! JavaScript must be enabled for proper operation of the Administrator backend.		</noscript>
		<div class="clr"></div>

	</div><!-- end content -->
  <div class="clr"></div>
</div>
<!-- end containerwrap --> 

<!-- Footer --> 
<div role="contentinfo" id="footer">
  <p align="center">DMA</p>
  <p class="copyright">
        </p>
</div>
<script>

</script>
</body></html>
